package com.lobo.blog.controller;

import com.lobo.blog.entity.Blog;
import com.lobo.blog.service.BlogService;
import com.lobo.blog.service.TagService;
import com.lobo.blog.service.TypeService;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;

import javax.annotation.Resource;

/**
 * @authoer:MacieSerenity
 * @createDate: 2022/9/24
 * @description:
 */
@Controller
public class IndexController {
    @Resource
    BlogService blogService;
    @Resource
    TypeService typeService;
    @Resource
    TagService tagService;

    @RequestMapping(value = "/", method = RequestMethod.GET)
    public String toIndex(Model model) {
        model.addAttribute("page", blogService.getBlogs(1));
        model.addAttribute("types", typeService.getTopTypeBySize(6));
        model.addAttribute("tags", tagService.getTopTagBySize(6));
        model.addAttribute("recentBlog", blogService.getRecentNewBlogBySize(6));
        return "index";
    }

    @RequestMapping(value = "/{pageNum}", method = RequestMethod.GET)
    public String toIndexPage(Model model,
                              @PathVariable("pageNum") Integer pageNum) {
        model.addAttribute("page", blogService.getBlogs(pageNum));
        model.addAttribute("types", typeService.getTopTypeBySize(6));
        model.addAttribute("tags", tagService.getTopTagBySize(6));
        model.addAttribute("recentBlog", blogService.getRecentNewBlogBySize(6));
        return "index";
    }


    @RequestMapping("/search/{pageNum}")
    public String search(@RequestParam String query,
                         @PathVariable Integer pageNum,
                         Model model) {
        if (pageNum == null) {
            pageNum = 1;
        }
        Blog blog = new Blog();
        blog.setTitle(query);
        model.addAttribute("page", blogService.findBlogsByQuery(pageNum, query));
        model.addAttribute("query", query);
        return "search";
    }


    @RequestMapping(value = "/aboutMe", method = RequestMethod.GET)
    public String toAboutMe() {
        return "about-me";
    }

}
